package top.yuki.Runnable;

import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection;
import top.yuki.LevelWorld;
import top.yuki.board.PlayerBoard;
import top.yuki.data.DataManager;
import top.yuki.data.DayDataManager;
import top.yuki.data.TempDataManage;

import java.io.File;
import java.util.*;

import static org.bukkit.Bukkit.getLogger;

public class AutoRefreshEssence {
    private LevelWorld lw;
    private DataManager dataManage ;
    private TempDataManage tempDataManage;
    private DayDataManager dayDataManager;
    private HashMap<String, HashMap> dataMap ;
    private ConfigurationSection config;
    public File dataFolder = null;

    public static AutoRefreshEssence init(LevelWorld lw) {

        return new AutoRefreshEssence(lw);
    }
    public AutoRefreshEssence(LevelWorld lw){
        this.lw = lw;
        this.dataFolder = lw.getDataFolder();
        this.dataManage = lw.dataManage;
        this.tempDataManage = lw.tempDataManage;
        this.dayDataManager = lw.dayDataManager;
        this.dataMap = dataManage.dataMap;
        this.config = lw.getConfig();
        getLogger().info("每"+Long.parseLong(config.getString("addEssenceTime"))/60000+"分钟刷新一次体力");
    }

    public void start()
    {

        TimerTask task = new TimerTask() { //创建一个新的timer task
            public void run() { //定时器任务执行的操作
                int readEssence = 0;
                int calMaxEssence = 0;
                getLogger().info("刷新体力,储存数据");
                for(String id:dataMap.keySet()){
                    readEssence = dataManage.getEssence(UUID.fromString(id));
                    calMaxEssence = dataManage.calMaxEssence(UUID.fromString(id));
                    if (readEssence < calMaxEssence){
                        dataManage.addEssence(UUID.fromString(id),1);
                    }
                    try {
                        PlayerBoard.refresh(Bukkit.getPlayer(UUID.fromString(id)));
                    } catch (Exception e) {
                    }
                }
                dataManage.save();
                dayDataManager.detectRefresh();
                dayDataManager.save();
                tempDataManage.tryRefreashData();

            }
        };
        Timer timer = new Timer();//创建一个定时器

        long delay = 0;
        long PeriodTime = Long.parseLong(config.getString("addEssenceTime"));
        timer.scheduleAtFixedRate(task, delay, PeriodTime);
        //重复执行特定任务，第一个参数为要执行的任务，第二个为执行任务之前延迟的时间，第三个为时间间隔
        //单位都是毫秒
    }
}